<!-- 游戏默认配置 -->
<template>
  <div style="height: 87.5vh;padding: 0;">
    <el-tabs v-model="data.gameType" type="card" class="demo-tabs" @tab-change="handleClick" style="user-select: none;">
      <el-tab-pane label="老虎机配置" :name="1" />
      <el-tab-pane label="百人场配置" :name="2" />
      <el-tab-pane label="全局表配置" :name="0" />
      <el-tab-pane label="游戏表配置" :name="-1" />
    </el-tabs>
    <SearchTable :query="data.query" :list="data.list" :total="data.total" :showFromQuery="data.gameType?false:true"
      @changeTh="data.dialogVisible = true" @changeSize="changeSize" @changePage="changePage"  @search="handleClick"
      @reset="resetDetails" style="padding: 0">
      <template #form>
        <el-form-item label="ID：" v-if="!data.gameType ? true : false">
          <el-input class="width240" type="text" v-model="data.globalQuery.id" placeholder="请输入数据ID" clearable />
        </el-form-item>
        <el-form-item label="备注：" v-if="!data.gameType ? true : false">
          <el-input class="width240" type="text" v-model="data.globalQuery.remark" placeholder="请输入备注" clearable />
        </el-form-item>
      </template>
      <template #button>
        <el-button class="marginR5" type="danger" v-permiss="'/system/destroyManager'" size="small" @click="data.isShowLoad = true">
          重载配置表
        </el-button>
        <el-button type="warning" v-show="data.gameType!=-1?true : false" v-permiss="'/system/destroyManager'" size="small"
          @click="initialConfiguration">
          初始化{{data.gameType==1? '老虎机配置':data.gameType==2? '百人场配置':'全局表配置'}}
        </el-button>
        <el-button v-if="data.gameType < 1? true : false" type="success" v-permiss="'/system/destroyManager'"
          @click="addDefaultConfig">
          新增默认配置
        </el-button>
        <el-button v-if="data.gameType ? true : false" type="danger" v-permiss="'/system/destroyManager'" size="small"
          @click="data.isShowCommercial = true">
          同步商户配置
        </el-button>
      </template>
      <template #table>
        <template v-for="(item, index) in data.fields" :key="index">
          <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width" show-overflow-tooltip>
            <template #header>
              <el-tooltip v-if="item.tips" effect="dark" placement="top">
                <template #content> {{ item.tips }} </template>
                <el-icon class="ques-tips">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
              {{ item.label }}
            </template>
            <template v-if="item.prop == 'game_name'" #default="scope">
              <div class="gameIcon">
                <div style="width: 48%;"><img class="game-icon" :src="selectToLabel(GAMEICON, scope.row.game_id)" alt=""></div>
                {{ selectToLabel(indexStore.gameArray, scope.row.game_id) }}
              </div>
            </template>
            <template v-if="item.prop == 'game_type'" #default="scope">
              <el-tag>{{ selectToLabel(GAMETYPE, scope.row.game_type) }}</el-tag>
            </template>
            <template v-if="item.prop == 'status'" #default="scope">
              <el-tag :type="scope.row.status?'success':'danger'">{{ selectToLabel(DEMOPLAY, scope.row.status) }}</el-tag>
            </template>
            <template v-if="item.prop == 'trial_path'" #default="scope">
              <div class="flexCenter">
                <p class="text-cut details" @click="copyUrl(scope.row.trial_path,false)" style="width: 280px;">{{ scope.row.trial_path }}</p>
                <el-tooltip v-if="scope.row.trial_path" effect="light" placement="top" content="复制试玩路径">
                  <el-button class="marginL10" round size="small" type="success" :icon="CopyDocument"
                    @click="copyUrl(scope.row.trial_path,true)" />
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </template>
        <el-table-column fixed="right" label="操作" width="240" align="center">
          <template #default="scope">
            <el-button type="primary" v-permiss="'/system/destroyManager'" size="small"
              @click="checkDetails(scope.row, 'check')">
              查 看
            </el-button>
            <el-button type="warning" v-permiss="'/system/destroyManager'" size="small"
              @click="checkDetails(scope.row, 'edit')">
              编 辑
            </el-button>
            <el-button v-if="!data.gameType? true : false" type="danger" v-permiss="'/system/destroyManager'" size="small"
              @click="coverDetails(scope.row)">
              同步商户
            </el-button>
          </template>
        </el-table-column>
      </template>
    </SearchTable>

    <!-- 变更表头弹框 -->
    <tableHeader :dialogVisible="data.dialogVisible" :list="data.fields" @cancel="data.dialogVisible = false"
      @resetData="resetData"></tableHeader>

    <!-- 默认配置 -->
    <Game :show="data.isShowGame" :showDisable="data.isDisableUser" :checkedItem="data.checkedGameItem" @onHideDetails="onHideDetails" />
    <Config :show="data.isShowDetails" :showDisable="data.isDisableUser" :showDefault="true" :checkedItem="data.checkedItem" @onHideDetails="onHideDetails" />

    <!-- 默认全局表配置 -->
    <Global :show="data.isShowGlobal" :showDisable="data.isDisableUser" :checkedItem="data.checkedGlobalItem"
      @onHideDetails="onHideDetails" />
    
    <!-- 重载表 -->
    <el-dialog v-model="data.isShowLoad" title="重载表" :close-on-click-modal="false" :close-on-press-escape="false"
      width="50%" top="25vh" @close="onHideDetails">
      <form-item title="表名" :pass="true" value="overloadTable">
        <el-select class="formItem240" v-model="data.overloadTable" placeholder="请选择表名" filterable>
          <el-option v-for="(item,index) in data.listTable" :key="index"
            :label="'【' + item.table_name + '】' + item.table_comment" :value="item.table_name" />
        </el-select>
      </form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="info" @click="onHideDetails">取 消</el-button>
          <el-button type="primary" @click="overload">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 同步商户配置 -->
    <el-dialog v-model="data.isShowCommercial" title="同步商户配置" :close-on-click-modal="false" :close-on-press-escape="false"
      width="50%" top="25vh" @close="onHideDetails">
      <form-item title="商户" :pass="true" value="agent_ids">
        <el-select class="imWidth100" v-model="data.commercialForm.agent_ids" placeholder="请选择商户" filterable multiple @change="chooseAgent">
          <el-option label="全部" :value="-1" />
          <el-option v-for="(item,index) in indexStore.agentArray" :key="index"
            :label="'【' + item.value + '】' + item.label" :value="item.value" />
        </el-select>
      </form-item>
      <form-item title="游戏" :pass="true" value="game_id" v-if="data.gameType ? true : false">
        <el-select class="imWidth100" v-model="data.commercialForm.game_id" placeholder="请选择游戏" filterable multiple @change="chooseGame">
          <el-option label="全部" :value="-1" />
          <el-option v-for="(item,index) in data.list as any" :key="index"
            :label="'【' + item.game_id + '】' + item.game_name" :value="item.game_id" />
        </el-select>
      </form-item>
      <form-item title="表格字段" :pass="true" value="params" v-if="data.gameType==1 || data.gameType==-1">
        <el-select class="imWidth100" v-model="data.commercialForm.params" placeholder="请选择字段" filterable multiple @change="chooseKey">
          <el-option label="全部" :value="-1" />
          <el-option v-for="(item,index) in data.gameType==1?data.tigerKey:data.gameKey" :key="index"
            :label="'【' + item.value + '】' + item.label" :value="item.value" />
        </el-select>
      </form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="info" @click="onHideDetails">取 消</el-button>
          <el-button type="primary" @click="initialSynchronization">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRefs, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CopyDocument } from '@element-plus/icons-vue'
import tableHeader from '@/components/tableHeader/tableHeader.vue'
import SearchTable from '@/components/SearchTable/SearchTable.vue'
import Game from '@/views/configManage/components/game.vue'
import FormItem from '@/components/FormItem/FormItem.vue'
import { 
  getGame, 
  getGlobal, 
  coverGlobal, 
  initializeGlobal,
  initializeSlot,
  initializeHundred, 
  initializeGame,
  getOverloadTable, 
  overloadTable,
  coverSlot,
  coverHundred,
  coverGame
 } from '@/api/game'
import { GAMETYPE,GAMEICON,DEMOPLAY } from '@/config/eunm'
import Config from '@/views/configManage/components/config.vue'
import Global from '@/views/configManage/components/global.vue'
import { selectToLabel } from '@/utils/index'
import { useStore } from '@/stores/index'
const indexStore = useStore()
const data = reactive({
  query: {
    page: 1,
    size: 50,
    game_type: 1,
    agent_id: 0,
  },
  list: [],
  total: 0,
  gameType: 1,
  fields: [
    { label: '游戏ID', prop: 'game_id', width: '240', visible: true, tips: '游戏的ID' },
    { label: '游戏类型', prop: 'game_type', width: '240', visible: true, tips: '此游戏的类型，区分为百人、MiniGame 、老虎机' },
    { label: '游戏名称', prop: 'game_name', width: '', visible: true, tips: '游戏名称的描述说明' },
  ],
  globalQuery: {
    page: 1,
    size: 50,
    agent_id: 0,
    id: '',
    remark: '',
  },
  dialogVisible: false,
  isShowDetails: false,
  isDisableUser: false,
  isShowCommercial: false,
  isShowGame: false,
  isShowGlobal: false,
  isShowLoad: false,
  overloadTable: '',
  listTable: [] as any[],
  commercialForm:{
    agent_ids: [],
    game_id: [],
    params:[]
  },
  checkedItem: {} as any,
  checkedGameItem: {} as any,
  checkedGlobalItem: {} as any,
  tigerKey:[
    { label: '备注',value: 'remark' },
    { label: '行',value: 'a_slots_row' },
    { label: '列',value: 'a_slots_column' },
    { label: '止损止赢开关',value: 'a_slots_auto' },
    { label: '赢取展示',value: 'a_slots_winshow' },
    { label: '游戏用线',value: 'a_slots_lineuse' },
    { label: '游戏wild元素ID',value: 'a_slots_wildid' },
    { label: '线倍率',value: 'a_slots_linemagnification' },
    { label: 'slots押注',value: 'a_slots_amount' },
    { label: '默认押注',value: 'a_slots_defaultamount' },
    { label: '后台RTP显示',value: 'a_slots_rtpshow' },
    { label: '初始RTP',value: 'a_slots_rtp' },
    { label: '小游戏图标',value: 'a_slots_scatterid' },
    { label: '赢取最高押注倍数',value: 'a_slots_maxwin' },
    { label: '购买小游戏功能',value: 'a_slots_buy' },
    { label: '关闭倍数(总押注超过最低押注的倍数关闭购买)',value: 'a_slots_multipleclose' },
    { label: '购买倍数(押注的倍数为购买花费)',value: 'a_slots_buymultiple' },
    { label: '游戏功能开启关闭',value: 'a_rtp_control' },
    { label: '多少次检测一次最新RTP',value: 'a_rtp_check' },
    { label: '控制配置:rtp范围,概率触发,使用RTP表',value: 'a_rtp_control_cfg' },
    { label: 'RTP在此范围不控制',value: 'a_rtp_setting' },
  ],
  gameKey:[
    { label: 'GameUrl',value: 'game_url' },
    { label: '试玩路径',value: 'trial_path' },
    { label: '游戏中文名',value: 'game_name' },
    { label: '游戏英文名',value: 'game_name_en' },
  ]
})

onMounted(async () => {
  getSearchList()
  getTableList()
})

const getSearchList = async () => {
  indexStore.setPageLoading(true)
  let res = await getGame(data.query)
  indexStore.setPageLoading(false)
  data.list = res.data.list
  data.total = res.data.total
}

const getGlobalList = async () => {
  let query = JSON.parse(JSON.stringify(data.globalQuery))
  query.id = Number(query.id)
  indexStore.setPageLoading(true)
  let res = await getGlobal(query)
  indexStore.setPageLoading(false)
  data.list = res.data.list
  data.total = res.data.total
}

const getTableList = async () => {
  let res = await getOverloadTable({})
  data.listTable = res.data
}

// 选择游戏tab
const handleClick = async () => {
  data.query.game_type = data.gameType
  if (data.gameType) {
    if(data.gameType==-1){
      data.fields = [
        { label: '游戏ID', prop: 'game_id', width: '120', visible: true, tips: '游戏的ID' },
        { label: '游戏名称', prop: 'game_name', width: '200', visible: true, tips: '游戏名称的描述说明' },
        { label: '游戏英文名称', prop: 'game_name_en', width: '220', visible: true, tips: '游戏名称的英文描述说明' },
        { label: '游戏类型', prop: 'game_type', width: '120', visible: true, tips: '此游戏的类型，区分为百人、MiniGame 、老虎机' },
        { label: '游戏状态', prop: 'status', width: '140', visible: true, tips: '此游戏的状态开启才可以进入，维护关闭' },
        { label: 'GameUrl', prop: 'game_url', width: '', visible: true, tips: '此游戏的GameUrl路径' },
        { label: '游戏试玩路径', prop: 'trial_path', width: '', visible: true, tips: '此游戏的游戏试玩路径' },
      ]
      data.query.agent_id = 0
    }else{
      data.fields = [
        { label: '游戏ID', prop: 'game_id', width: '180', visible: true, tips: '游戏的ID' },
        { label: '游戏类型', prop: 'game_type', width: '150', visible: true, tips: '此游戏的类型，区分为百人、MiniGame 、老虎机' },
        { label: '游戏名称', prop: 'game_name', width: '', visible: true, tips: '游戏名称的描述说明' },
      ]
    }
  } else {
    data.fields = [
      { label: 'ID', prop: 'id', width: '90', visible: true, tips: '此数据的ID' },
      { label: '备注', prop: 'remark', width: '380', visible: true, tips: '此数据的备注' },
      { label: '参数', prop: 'a_global_parameter', width: '', visible: true, tips: '此数据的参数' },
    ]
  }
  onHideDetails(false)
}

// 初始化配置 老虎机1 百人场2 捕鱼3 街机4 
const initialConfiguration = async () => {
  let message = '是否初始化默认配置？';
  ElMessageBox.confirm(message, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    if(data.gameType == 1){
      await initializeSlot({})
    }else if(data.gameType == 2){
      await initializeHundred({})
    }else{
      await initializeGlobal({})
    }
    ElMessage.success('初始化成功')
    onHideDetails(true)
  }).catch(() => { })
}

// 重载表
const overload = async () => {
  if(data.overloadTable){
    let name= ''
    data.listTable.forEach((item:any)=>{
      if(data.overloadTable == item.table_name){
        name = item.table_comment
      }
    })
    ElMessageBox.confirm(`是否重载【${data.overloadTable}】${name}`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }).then(async () => {
      await overloadTable({table_name:data.overloadTable})
      ElMessage.success('重载成功')
      onHideDetails(false)
    }).catch(() => { })
  }
}

// 新增默认配置
const addDefaultConfig = async () => {
  if (data.gameType) {
    data.isShowDetails = true
  } else {
    data.isShowGlobal = true
  }
}

// 复制试玩路径
const copyUrl = (url: string, type: boolean) => {
  if(type){
    let oInput = document.createElement("input");
    oInput.value = url
    document.body.appendChild(oInput)
    oInput.select() //选择对象
    document.execCommand("Copy") //执行浏览器复制命令
    document.body.removeChild(oInput)
    ElMessage.success('复制成功')
  }else{
    window.open(url)
  }
}

// 详情
const checkDetails = async (row: any, type: string) => {
  if (type == 'check') {
    data.isDisableUser = true
  } else {
    data.isDisableUser = false
  }
  if (data.gameType) {
    if(data.gameType==-1){
      data.isShowGame = true
      data.checkedGameItem = row
    }else{
      data.isShowDetails = true
      Object.assign(data.checkedItem, row)
    }
  } else {
    data.checkedGlobalItem = row
    data.isShowGlobal = true
  }
}

// 选择商户 + 游戏 + 字段
const chooseAgent = async (row: any) => {
  const all = row.find((item:number) => item == -1)
  if(all){
    data.commercialForm.agent_ids=[ -1 ] as any
  }else{
    data.commercialForm.agent_ids = row
  }
}
const chooseGame = async (row: any) => {
  const all = row.find((item:number) => item == -1)
  if(all){
    data.commercialForm.game_id=[ -1 ] as any
  }else{
    data.commercialForm.game_id = row
  }
}
const chooseKey = async (row: any) => {
  const all = row.find((item:number) => item == -1)
  if(all){
    data.commercialForm.params=[ -1 ] as any
  }else{
    data.commercialForm.params = row
  }
}

// 同步配置-详情
const coverDetails = async (row: any) => {
  data.isShowCommercial = true
  Object.assign(data.checkedGameItem, row)
}

// 商户同步配置
const initialSynchronization = async () => {
  const parameter = JSON.parse(JSON.stringify(data.commercialForm))
  if(!parameter.agent_ids.length){
    return ElMessage.error('请选择商户')
  }
  if(!parameter.game_id.length && data.gameType){
    return ElMessage.error('请选择游戏')
  }
  if(!parameter.params.length && data.gameType==1){
    return ElMessage.error('请选择表格字段')
  }
  let message = '是否将配置同步到选择的商户？';
  const all = data.commercialForm.agent_ids.find((item:number) => item == -1)
  const allGame = data.commercialForm.game_id.find((item:number) => item == -1)
  const allKey = data.commercialForm.params.find((item:number) => item == -1)
  if(all){
    parameter.agent_ids = []
    indexStore.agentArray.forEach((item:any)=>{
      parameter.agent_ids.push(item.value)
    })
  }
  if(allGame){
    parameter.game_id = []
    indexStore.gameArray.forEach((item:any)=>{
      parameter.game_id.push(item.value)
    })
  }
  if(allKey){
    parameter.params = []
    if(data.gameType == 1){
      data.tigerKey.forEach((item:any)=>{
        parameter.params.push(item.value)
      })
    }else{
      data.gameKey.forEach((item:any)=>{
        parameter.params.push(item.value)
      })
    }
  }
  ElMessageBox.confirm(message, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    switch (data.gameType) {
      case -1:
        await coverGame(parameter)
      break;
      case 0:
        let query = JSON.parse(JSON.stringify(data.checkedGameItem))
        query.agent_id = parameter.agent_ids
        await coverGlobal(query)
      break;
      case 1:
        await coverSlot(parameter)
      break;
      case 2:
        await coverHundred(parameter)
      break;
    }
    ElMessage.success('同步成功')
    onHideDetails(true)
  }).catch(() => { })
}

// 修改页数
const changeSize = (val: number) => {
  if (data.gameType) {
    data.query.size = val
    getSearchList()
  }else{
    data.globalQuery.size = val
    getGlobalList()
  }
}

const changePage = (val: number) => {
  if (data.gameType) {
    data.query.page = val
    getSearchList()
  }else{
    data.globalQuery.page = val
    getGlobalList()
  }
}

// 重置表头
const resetData = (val: any) => {
  data.fields = val
}

// 重置
const onHideDetails = (show: boolean) => {
  data.isShowDetails = false
  data.isDisableUser = false
  data.dialogVisible = false
  data.isShowGame = false
  data.isShowGlobal = false
  data.isShowLoad = false
  data.isShowCommercial = false
  data.overloadTable = ''
  data.commercialForm ={
    agent_ids: [],
    game_id: [],
    params:[]
  }
  data.checkedGameItem = {} as any
  data.checkedGlobalItem = {} as any
  if (show) {
    data.globalQuery = {
      page: data.query.page,
      size: data.query.size,
      agent_id: data.globalQuery.agent_id,
      id: data.globalQuery.id,
      remark: data.globalQuery.remark,
    }
    if (data.gameType) {
      getSearchList()
    } else {
      getGlobalList()
    }
  }
}
const resetDetails = () => {
  data.globalQuery = {
    page: 1,
    size: 50,
    agent_id: 0,
    id: '',
    remark: '',
  }
  if (data.gameType) {
    getSearchList()
  } else {
    getGlobalList()
  }
}
</script>

<style scoped lang="scss"></style>
